package cq.zhcqk.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.bean.BuildBean;
import com.dou361.dialogui.bean.TieBean;
import com.dou361.dialogui.listener.DialogUIDateTimeSaveListener;
import com.dou361.dialogui.listener.DialogUIItemListener;
import com.dou361.dialogui.listener.DialogUIListener;
import com.dou361.dialogui.widget.DateSelectorWheelView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.apache.http.Header;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cq.zhcqk.R;
import cq.zhcqk.base.BaseActivity;
import cq.zhcqk.util.AsyncHttpClientUtils;
import cq.zhcqk.util.Common;
import cq.zhcqk.util.GsonUtil;
import cq.zhcqk.util.ImageLoaderHelper;
import cq.zhcqk.util.SpUtil;
import cq.zhcqk.util.StringUtil;
import cq.zhcqk.util.ToastUtil;
import cq.zhcqk.util.Utils;

/**
 * Created by zhangle on 2017/12/10.
 */
public class MinexxActivity extends AppCompatActivity implements View.OnClickListener{
    private TextView phone;
    private TextView nick_name;
    private RoundedImageView headImgView;
    private LinearLayout nick_lay;
    private Button update;

    private static int CAMERA_REQUEST_COOE = 1;
    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    private static final int CROP_SMALL_PICTURE = 2;
    protected static Uri tempUri;
    private Bitmap headBit = null;
    String imagePath;

    String nickName = "";
    String fileName = "";
    Uri uritempFile;

    private Context context;
    protected SharedPreferences mSharedPreferences;
    protected AsyncHttpClient httpClient;
    private Dialog dialog;
    protected BuildBean buildBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_xx);
        context = this;
        mSharedPreferences = SpUtil.getSpBykey(context, SpUtil.TOKEN);
        httpClient = AsyncHttpClientUtils.getInstance().getAsyncHttpClient();
        buildBean = DialogUIUtils.showLoading(this, "加载中...", true, true, true, false);
        initBack();
        phone = (TextView) findViewById(R.id.phone);
        nick_name = (TextView) findViewById(R.id.nick_name);
        nick_lay = (LinearLayout) findViewById(R.id.nick_lay);
        update = (Button) findViewById(R.id.update);
        headImgView = (RoundedImageView) findViewById(R.id.head);

        headImgView.setOnClickListener(this);
        nick_lay.setOnClickListener(this);
        nick_name.setOnClickListener(this);
        update.setOnClickListener(this);

        initData();
    }

    protected void initData() {
        phone.setText(mSharedPreferences.getString("phone",null));
        String headImg = mSharedPreferences.getString("picaddress",null);
        String nick = mSharedPreferences.getString("var01",null);
        if(headImg != null){
            ImageLoader.getInstance().displayImage(Common.URL+headImg , headImgView, ImageLoaderHelper.getOptionsHead());
        }
        if(nick != null){
            nick_name.setText(nick);
        }
    }

    private void initBack(){
        ImageView back = (ImageView) findViewById(R.id.header_back);
        TextView title = (TextView) findViewById(R.id.header_text);
        title.setText("个人信息");
        back.setOnClickListener(this);
    }

    private void showChoose(){
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View rootView = layoutInflater.inflate(R.layout.custom_dialog_photo, null);
        dialog = DialogUIUtils.showCustomAlert(context, rootView, Gravity.CENTER, true, true).show();
        rootView.findViewById(R.id.xiangce).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent;
                if (Build.VERSION.SDK_INT < 19) {
                    intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                } else {
                    intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                }
//                Intent openAlbumIntent = new Intent(
//                        Intent.ACTION_GET_CONTENT);
//                openAlbumIntent.setType("image/*");
                startActivityForResult(intent, CHOOSE_PICTURE);
                dialog.dismiss();
            }
        });
        rootView.findViewById(R.id.xiangji).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent openCameraIntent = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                tempUri = Uri.fromFile(new File(Environment
                        .getExternalStorageDirectory(), "image.png"));
                // 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
                startActivityForResult(openCameraIntent, TAKE_PICTURE);
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) { // 如果返回码是可以用的
            switch (requestCode) {
                case TAKE_PICTURE:
                    startPhotoZoom(tempUri); // 开始对图片进行裁剪处理
                    break;
                case CHOOSE_PICTURE:
                    startPhotoZoom(data.getData()); // 开始对图片进行裁剪处理
                    break;
                case CROP_SMALL_PICTURE:
                    if (data != null) {
                        setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
                    }
                    break;
            }
        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    protected void startPhotoZoom(Uri uri) {
        if (uri == null) {
            Log.i("tag", "The uri is not exist.");
        }
        tempUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
//        intent.putExtra("return-data", true);

        /**
         * 此方法返回的图片只能是小图片（sumsang测试为高宽160px的图片）
         * 故只保存图片Uri，调用时将Uri转换为Bitmap，此方法还可解决miui系统不能return data的问题
         */
        //intent.putExtra("return-data", true);

        //裁剪后的图片Uri路径，uritempFile为Uri类变量
        uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        startActivityForResult(intent, CROP_SMALL_PICTURE);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param
     *
     */
    protected void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
//        if (extras != null) {
            //将Uri图片转换为Bitmap
            try {
                Bitmap photo = BitmapFactory.decodeStream(getContentResolver().openInputStream(uritempFile));
//                Bitmap photo = extras.getParcelable("data");
                headImgView.setImageBitmap(photo);
                headBit = photo;
                uploadPic(photo);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
//        }
    }

    private void uploadPic(Bitmap bitmap) {
        // 上传至服务器
        // ... 可以在这里把Bitmap转换成file，然后得到file的url，做文件上传操作
        // 注意这里得到的图片已经是圆形图片了
        // bitmap是没有做个圆形处理的，但已经被裁剪了

        imagePath = Utils.savePhoto(bitmap, Environment
                .getExternalStorageDirectory().getAbsolutePath(), String
                .valueOf(System.currentTimeMillis()));
        Log.e("imagePath", imagePath+"");
        if(imagePath != null){
            // 拿着imagePath上传了
            try {
                upFile(imagePath);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    private void upFile(String uri) throws FileNotFoundException {
        RequestParams params = new RequestParams();
        //上传文件
        params.put("file", new File(uri));
        httpClient.post(Common.URL+Common.UPLOAD1,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                fileName = map.get("fileName")+"";
                if(fileName != null && !"".equals(fileName)){
                    Toast.makeText(context,"上传成功",Toast.LENGTH_SHORT).show();
//                    SharedPreferences.Editor editor = mSharedPreferences.edit();
//                    editor.putString("picaddress",map.get("fileName")+"");
//                    editor.commit();
                }else{
                    Toast.makeText(context,"上传失败，请稍后再试",Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("errorResponse："+errorResponse);
                Toast.makeText(context,"上传失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                System.out.println("responseString："+responseString);
                Toast.makeText(context,"上传失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUIUtils.dismiss(buildBean);
            }
        });
    }

    private void upName(){
        DialogUIUtils.showAlert(this, "设置昵称", "", "","请输入用户名",  "确定", "取消", false, true, true, new DialogUIListener() {
            @Override
            public void onPositive() {
                nick_name.setText(nickName);
            }

            @Override
            public void onNegative() {

            }

            @Override
            public void onGetInput(CharSequence input1, CharSequence input2) {
                super.onGetInput(input1, input2);
                nickName = (String) input2;
                nick_name.setText(nickName);
            }
        }).show();
    }

    private void upUserInfo() {
        RequestParams params = new RequestParams();
        nickName = nick_name.getText().toString();
        params.put("nickName",nickName);
        if(StringUtil.isNull(fileName)){
            fileName = mSharedPreferences.getString("picaddress",null);
        }
        params.put("picaddress",fileName);
        httpClient.post(Common.URL+Common.SETNAME,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");

                if(StringUtil.stringToInt(map.get("code")+"") == 0){
                    Toast.makeText(context,"修改成功",Toast.LENGTH_SHORT).show();
                    SharedPreferences.Editor editor = mSharedPreferences.edit();
                    if(!StringUtil.isNull(fileName)){
                        editor.putString("picaddress",fileName);
                    }
                    if(!StringUtil.isNull(nickName)){
                        editor.putString("var01",nickName);
                    }
                    editor.commit();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("errorResponse："+errorResponse);
                Toast.makeText(context,"修改失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                System.out.println("responseString："+responseString);
                Toast.makeText(context,"修改失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUIUtils.dismiss(buildBean);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.header_back:
                finish();
                break;
            case R.id.head:
                showChoose();
                break;
            case R.id.nick_lay:
                upName();
                break;
            case R.id.update:
                upUserInfo();
                break;
        }
    }
}
